package website.lucaswork.survey.core.services.impls;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;
import website.lucaswork.survey.core.daos.SurveyRepository;
import website.lucaswork.survey.core.dtos.DtoFactory;
import website.lucaswork.survey.core.dtos.SurveySummaryDTO;
import website.lucaswork.survey.core.entities.Survey;
import website.lucaswork.survey.core.entities.User;
import website.lucaswork.survey.core.services.SurveyService;

@Transactional
@Service(value = "surveyService")
public class SurveyServiceImpl implements SurveyService {

    @Autowired
    SurveyRepository surveyRepo;

    @Autowired
    DtoFactory dtoFactory;

    @Override
    public SurveySummaryDTO getSurveyInfo(int id) {
        Survey survey = surveyRepo.findOne(id);
        return dtoFactory.produceSurveySummaryDTO(survey);
    }

    @Override
    public Page<SurveySummaryDTO> getPageSurveys(Pageable pageable) {
        Page<Survey> surveys = surveyRepo.findAll(pageable);
        List<SurveySummaryDTO> ret = new ArrayList<SurveySummaryDTO>();
        for (Survey survey : surveys) {
            ret.add(dtoFactory.produceSurveySummaryDTO(survey));
        }
        return new PageImpl<SurveySummaryDTO>(ret, pageable, surveys.getTotalElements());
    }

    @Override
    public Page<SurveySummaryDTO> getSearchPageSurveys(String keyword, Pageable pageable) {
        Page<Survey> surveys = surveyRepo.findByTitleContainingOrDescriptionContaining(keyword, keyword, pageable);
        List<SurveySummaryDTO> ret = new ArrayList<SurveySummaryDTO>();
        for (Survey survey : surveys) {
            ret.add(dtoFactory.produceSurveySummaryDTO(survey));
        }
        return new PageImpl<SurveySummaryDTO>(ret, pageable, surveys.getTotalElements());
    }

    @Override
    public Survey saveSurvey(Survey survey) {
        return surveyRepo.saveAndFlush(survey);
    }

    @Override
    public Survey getSurveyByTitleAndUser(String title, User user) {
        if (StringUtils.isEmpty(title) || user == null) {
            return null;
        }
        return surveyRepo.findByTitleAndUser(title, user);
    }

    @Override
    public Survey getSruveyBySlug(String slug) {
        if (StringUtils.isEmpty(slug)) {
            return null;
        }
        return surveyRepo.findBySlug(slug);
    }
}
